<script>
  import ajax from "./ajax";
  import UploadDragger from "./upload-dragger.vue";
  import ElProgress from 'element-ui/packages/progress';
  export default {
    inject: ["uploader"],
    components: {
      UploadDragger,
      ElProgress
    },
    props: {
      progressValue:{
        type:Number,
        default:0
      },
      showFileList:{
        type:Boolean
      },
      progressWidth:{
        type:Number,
        default:100
      },
      // 金山云input节点id      
      dcdom: {
        type: String,
        default: "dcFile"
      },
      // 金山云初始化配置
      dcConfig: {
        type: Object
      },
      // 金山云上传初始化接口函数
      dcUploadInit:{
        type:Object
      },
      // 金山云是否自动上传
      dcAutoUpload:Boolean,
      type: String,
      action: {
        type: String,
      },
      name: {
        type: String,
        default: "file"
      },
      data: Object,
      headers: Object,
      withCredentials: Boolean,
      multiple: Boolean,
      accept: String,
      onStart: Function,
      onProgress: Function,
      onSuccess: Function,
      onError: Function,
      beforeUpload: Function,
      drag: Boolean,
      onPreview: {
        type: Function,
        default: function() {}
      },
      onRemove: {
        type: Function,
        default: function() {}
      },
      fileList: Array,
      autoUpload: Boolean,
      listType: String,
      httpRequest: {
        type: Function,
        default: ajax
      },
      disabled: Boolean,
      limit: Number,
      onExceed: Function
    },
    data() {
      return {
        timer:null,
        percentageNumber:0,
        progressTrue:false,
        // 金山云上传文件信息(type,size,name)
        dcUploadData:{},
        domsize:'',
        mouseover: false,
        reqs: {}
      };
    },

    methods: {
      isImage(str) {
        return str.indexOf("image") !== -1;
      },
      handleChange(ev) {
        this.domsize = ev.target.id;
        const files = ev.target.files;
        this.$parent.dcChange(files[0]);
        if (!files) return;
        this.uploadFiles(files);
      },
      uploadFiles(files,dom) {
        if (this.limit && this.fileList.length + files.length > this.limit) {
          this.$message({message: '上传文件超过了限制',type: 'warning'});
          this.onExceed && this.onExceed(files, this.fileList);
          return;
        }

        let postFiles = Array.prototype.slice.call(files);
        if (!this.multiple) {
          postFiles = postFiles.slice(0, 1);
        }

        if (postFiles.length === 0) {
          return;
        }

        const before = !this.beforeUpload || this.beforeUpload(files);
        if(!before) return;
        postFiles.forEach(rawFile => {
          this.onStart(rawFile);
        });
        if (this.dcAutoUpload && before) this.post(files);
      },
      upload(rawFile) {
        this.beforeUpload();
        this.$refs.input.value = null;
        if (!this.beforeUpload) {
          this.$parent.dcChange(files[0]);
          return this.post(rawFile);
        }
        if (before && before.then) {
          // before.then(
          //   processedFile => {
          //     const fileType = Object.prototype.toString.call(processedFile);

          //     if (fileType === "[object File]" || fileType === "[object Blob]") {
          //       if (fileType === "[object Blob]") {
          //         processedFile = new File([processedFile], rawFile.name, {
          //           type: rawFile.type
          //         });
          //       }
          //       for (const p in rawFile) {
          //         if (rawFile.hasOwnProperty(p)) {
          //           processedFile[p] = rawFile[p];
          //         }
          //       }
          //       this.post(processedFile);
          //     } else {
          //       this.post(rawFile);
          //     }
          //   },
          //   () => {
          //     this.onRemove(null, rawFile);
          //   }
          // );
        } else if (before !== false) {
          this.post(rawFile);
        } else {
          this.onRemove(null, rawFile);
        }
      },
      abort(file) {
        const { reqs } = this;
        if (file) {
          let uid = file;
          if (file.uid) uid = file.uid;
          if (reqs[uid]) {
            reqs[uid].abort();
          }
        } else {
          Object.keys(reqs).forEach(uid => {
            if (reqs[uid]) reqs[uid].abort();
            delete reqs[uid];
          });
        }
      },
      post(rawFile) {
        this.$parent.dcUploadHttp(this.domsize);
        this.progressTrue = true;
        this.percentageNumber = this.progressValue;
        this.progressInit();
        // let fileInfo = document.getElementById(this.dcdom);
        // const { uid } = rawFile;
        // const options = {
        //   data: this.dcUploadData,
        //   onProgress: e => {
        //     this.onProgress(e, rawFile);
        //   },
        //   onSuccess: res => {
        //     this.onSuccess(res, rawFile);
        //     delete this.reqs[uid];
        //   },
        //   onError: err => {
        //     this.onError(err, rawFile);
        //     delete this.reqs[uid];
        //   }
        // };
        // const req = this.httpRequest(options);
        // this.reqs[uid] = req;
        // if (req && req.then) {
        //   req.then(options.onSuccess, options.onError);
        // }
      },
      // 上传中
      progressInit(){
        this.timer = setInterval(() => {
          this.percentageNumber += 9;
          if(this.percentageNumber > 90){
            clearInterval(this.timer);
          }
        }, 180);
      },
      // 上传结束
      progressEnd(){
        clearInterval(this.timer);
        this.progressTrue = false;
      },
      handleClick() {
        if (!this.disabled) {
          this.$refs.input.value = null;
          this.$refs.input.click();
        }
      },
      handleKeydown(e) {
        if (e.target !== e.currentTarget) return;
        if (e.keyCode === 13 || e.keyCode === 32) {
          this.handleClick();
        }
      }
    },

    render(h) {
      let {
        showFileList,
        progressWidth,
        progressTrue,
        percentageNumber,
        dcdom,
        dcConfig,
        handleClick,
        drag,
        name,
        handleChange,
        multiple,
        accept,
        listType,
        uploadFiles,
        disabled,
        handleKeydown
      } = this;
      const data = {
        class: {
          "el-upload": true
        },
        on: {
          click: handleClick,
          keydown: handleKeydown
        }
      };
      data.class[`el-upload--${listType}`] = true;
      return (
        <div {...data} tabindex="0">
          {drag ? (
            <upload-dragger disabled={disabled} on-file={uploadFiles}>
              {this.$slots.default}
            </upload-dragger>
          ) : (
            this.$slots.default
          )}
          <input
            id={dcdom}
            class="el-upload__input"
            type="file"
            ref="input"
            name={name}
            on-change={handleChange}
            multiple={multiple}
            accept={accept}
          />
          {progressTrue && !showFileList?(
            <el-progress
              type={'circle'}
              width={progressWidth}
              percentage={percentageNumber}
            >
            </el-progress>
          ):null}
        </div>
      );
    },
    mounted () {
      // this.dcAutoInit();
    }
  };
</script>
<style lang="scss" scoped>
.el-progress{
  position: absolute;
  top: 0;
  left: 0;
}
</style>
